package com.brother.util;

import java.util.ArrayList;
import java.util.List;

import com.brother.model.LatLngPoint;

public class PointIntersect {
	
	public static boolean isInsidePolygon(String data, LatLngPoint p){
		List<LatLngPoint> points = new ArrayList<LatLngPoint>();
		String[] all = data.split(";");
		for(int i=0; i < all.length; i++){
			String[] point = all[i].split(",");
			float lng = Float.parseFloat(point[0]);
			float lat = Float.parseFloat(point[1]);
			points.add(new LatLngPoint(lat, lng));
		}
		return isInsidePolygon(points, p);
	}	
	
/**Determining if a point lies on the interior of a polygon
 * Refer to http://local.wasp.uwa.edu.au/~pbourke/geometry/insidepoly/
 * @param points
 * @param p
 * @return
 */
public static boolean isInsidePolygon(List<LatLngPoint> points, LatLngPoint p)
	{
	  int counter = 0;
	  int i;
	  float xinters;
	  LatLngPoint p1,p2;

	  int size = points.size();
	  
	  p1 = points.get(0);
	  for (i=1;i<=size;i++) {
	    p2 = points.get(i % size);
	    if (p.getLat() > Math.min(p1.getLat(),p2.getLat())) {
	      if (p.getLat() <= Math.max(p1.getLat(),p2.getLat())) {
	        if (p.getLng() <= Math.max(p1.getLng(),p2.getLng())) {
	          if (p1.getLat() != p2.getLat()) {
	            xinters = (p.getLat()-p1.getLat())*(p2.getLng()-p1.getLng())/(p2.getLat()-p1.getLat())+p1.getLng();
	            if (p1.getLng() == p2.getLng() || p.getLng() <= xinters)
	              counter++;
	          }
	        }
	      }
	    }
	    p1 = p2;
	  }

	  if (counter % 2 == 0)
	    return false;
	  else
	    return true;
	}
}

/*int InsidePolygon(Point *polygon,int N,Point p)
{
  int counter = 0;
  int i;
  double xinters;
  Point p1,p2;

  p1 = polygon[0];
  for (i=1;i<=N;i++) {
    p2 = polygon[i % N];
    if (p.y > MIN(p1.y,p2.y)) {
      if (p.y <= MAX(p1.y,p2.y)) {
        if (p.x <= MAX(p1.x,p2.x)) {
          if (p1.y != p2.y) {
            xinters = (p.y-p1.y)*(p2.x-p1.x)/(p2.y-p1.y)+p1.x;
            if (p1.x == p2.x || p.x <= xinters)
              counter++;
          }
        }
      }
    }
    p1 = p2;
  }

  if (counter % 2 == 0)
    return(OUTSIDE);
  else
    return(INSIDE);
}*/
